<template>
  <div class="supplier-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="sreach" class="search-form">
        <el-form-item label="供应商编码">
          <el-input v-model="sreach.supplierCode" placeholder="请输入供应商编码" clearable />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="sreach.supplierName" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item label="供应商简称">
          <el-input v-model="sreach.supplierReferred" placeholder="请输入供应商简称" clearable />
        </el-form-item>
        <el-form-item label="供应商评分">
          <el-input v-model="sreach.supplierRating" placeholder="请输入供应商评分" clearable />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="sreach.isLock" placeholder="请选择状态" style="width: 200px;" clearable>
            <el-option label="是" value="0" />
            <el-option label="否" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="funShow">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">供应商列表</span>
          <el-button type="primary" @click="OpenAdd">
            <el-icon><Plus /></el-icon>新增供应商
          </el-button>
        </div>
      </template>

      <el-table
        :data="tableData"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="supplierCode" label="供应商编码" min-width="120" />
        <el-table-column prop="supplierName" label="供应商名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="supplierReferred" label="供应商简称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="supplierLevel" label="供应商等级" min-width="100">
          <template #default="scope">
            <el-tag :type="getSupplierLevelType(scope.row.supplierLevel)">
              {{ getSupplierLevelLabel(scope.row.supplierLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplierRating" label="供应商评分" min-width="100">
          <template #default="scope">
            <el-rate
              v-model="scope.row.supplierRating"
              :max="10"
              :low-threshold="4"
              :high-threshold="8"
              :colors="['#F56C6C', '#E6A23C', '#67C23A']"
              disabled
              style="margin-top: 4px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="supplierPhone" label="供应商电话" min-width="120" />
        <el-table-column prop="isLock" label="是否启用" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isLock"
              :active-value="0"
              :inactive-value="1"
              active-text="是"
              inactive-text="否"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="descs" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :total="page.totalCount"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="form.id ? '编辑供应商' : '新增供应商'"
      width="900px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="supplier-form"
        :status-icon="true"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编号" prop="supplierCode">
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商简称" prop="supplierReferred">
              <el-input v-model="form.supplierReferred" placeholder="请输入供应商简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商英文名称">
              <el-input v-model="form.supplierEngName" placeholder="请输入供应商英文名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="供应商简介">
          <el-input
            v-model="form.supplierDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入供应商简介"
          />
        </el-form-item>

        <el-form-item label="供应商地址">
          <el-input
            v-model="form.supplierAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入供应商地址"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商等级" prop="supplierLevel">
              <el-select v-model="form.supplierLevel" placeholder="请选择供应商等级">
                <el-option label="正常" :value="1" />
                <el-option label="优质供应商" :value="2" />
                <el-option label="一般供应商" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商评分" prop="supplierRating">
              <el-input-number
                v-model="form.supplierRating"
                :min="1"
                :max="10"
                :precision="1"
                :step="0.5"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="官网地址">
              <el-input v-model="form.websiteAddress" placeholder="请输入官网地址" clearable>
                <template #prefix>
                  <el-icon><Link /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱地址">
              <el-input v-model="form.websiteEmail" placeholder="请输入邮箱地址" clearable>
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="supplierPhone">
              <el-input v-model="form.supplierPhone" placeholder="请输入联系电话" clearable>
                <template #prefix>
                  <el-icon><Phone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">联系人信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系人1">
              <el-input v-model="form.firstName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人1电话">
              <el-input v-model="form.firstPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人1邮箱">
              <el-input v-model="form.firstEmail" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="联系人2">
              <el-input v-model="form.secondName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人2电话">
              <el-input v-model="form.secondPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人2邮箱">
              <el-input v-model="form.secondEmail" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="信用代码">
              <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="isLock">
              <el-radio-group v-model="form.isLock">
                <el-radio :value="0">是</el-radio>
                <el-radio :value="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="LOGO地址">
              <el-input v-model="form.logoAddress" placeholder="请输入LOGO地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form-item label="备注">
          <el-input
            v-model="form.descs"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
      </el-form-item>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Link, Message, Phone } from '@element-plus/icons-vue'
import axios from 'axios'
import http from '@/api/http'

// 加载状态
const loading = ref(false)

// 供应商等级映射
type SupplierLevel = '1' | '2' | '3'
interface LevelConfig {
  label: string
  type: string
}

const supplierLevelMap: Record<SupplierLevel, LevelConfig> = {
  '1': { label: '正常', type: '' },
  '2': { label: '优质供应商', type: 'success' },
  '3': { label: '一般供应商', type: 'warning' }
}

// 获取供应商等级标签
const getSupplierLevelLabel = (level: string) => {
  return supplierLevelMap[level as SupplierLevel]?.label || '未知'
}

// 获取供应商等级类型
const getSupplierLevelType = (level: string) => {
  return supplierLevelMap[level as SupplierLevel]?.type || 'info'
}

// 处理状态变更
interface SupplierRow {
  id: number
  isLock: number
  [key: string]: any
}

const handleStatusChange = async (row: SupplierRow) => {
  try {
    loading.value = true
    await http.post('api/MasterData/UpdateSupplier', row)
    ElMessage.success('状态更新成功')
  } catch (error: any) {
    ElMessage.error('状态更新失败：' + error.message)
    // 回滚状态
    row.isLock = row.isLock === 0 ? 1 : 0
  } finally {
    loading.value = false
  }
}

// 查询条件
const sreach = reactive({
  supplierCode: '',
  supplierName: '',
  supplierReferred: '',
  isLock: '',
  supplierRating: '',
})

// 分页条件
const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPage: 0
})

// 表单校验规则
const rules = {
  supplierCode: [{ required: true, message: '请输入供应商编号', trigger: 'blur' }],
  supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
  supplierReferred: [{ required: true, message: '请输入供应商简称', trigger: 'blur' }],
  supplierLevel: [{ required: true, message: '请选择供应商等级', trigger: 'change' }],
  supplierRating: [{ required: true, message: '请输入供应商评分', trigger: 'blur' }],
  isLock: [{ required: true, message: '请选择是否启用', trigger: 'change' }],
}

// 表单参数
const form = reactive({
  id:0,
  supplierCode: '',
  supplierName: '',
  supplierReferred: '',
  supplierEngName: '',
  supplierDesc: '',
  supplierAddress: '',
  supplierLevel: '',
  supplierRating: 1,
  websiteAddress: '',
  websiteEmail: '',
  supplierPhone: '',
  firstName: '',
  firstPhone: '',
  firstEmail: '',
  secondName: '',
  secondPhone: '',
  secondEmail: '',
  creditCode: '',
  isLock: 0,
  logoAddress: '',
  supplierImg: '',
  descs: '',
})

// 表单ref
const formRef = ref()

// 供应商信息显示
const tableData = ref([])
const funShow = async () => {
  try {
    loading.value = true
    const res = await axios.get('http://localhost:9991/api/MasterData/GetSupplierList', {
      params: {
        pageIndex: page.pageIndex,
        pageSize: page.pageSize,
        supplierCode: sreach.supplierCode,
        supplierName: sreach.supplierName,
        supplierReferred: sreach.supplierReferred,
        isLock: sreach.isLock,
        supplierRating: sreach.supplierRating,
      }
    })
    tableData.value = res.data.data
    page.totalCount = res.data.totalCount
    page.totalPage = res.data.totalPages
  } catch (error: any) {
    ElMessage.error('获取数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

//分页监听
watch(page,()=>{
  funShow()
})

// 重置搜索
const resetSearch = () => {
  Object.assign(sreach, {
    supplierCode: '',
    supplierName: '',
    supplierReferred: '',
    isLock: '',
    supplierRating: '',
  })
  funShow()
}

// 打开新增弹窗
const dialogFormVisible = ref(false)
const OpenAdd = () => {
  dialogFormVisible.value = true
  Object.assign(form, {
    supplierCode: '',
    supplierName: '',
    supplierReferred: '',
    supplierEngName: '',
    supplierDesc: '',
    supplierAddress: '',
    supplierLevel: '',
    supplierRating: 1,
    websiteAddress: '',
    websiteEmail: '',
    supplierPhone: '',
    firstName: '',
    firstPhone: '',
    firstEmail: '',
    secondName: '',
    secondPhone: '',
    secondEmail: '',
    creditCode: '',
    isLock: 0,
    logoAddress: '',
    supplierImg: '',
    descs: '',
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      funAdd()
    }
  })
}

// 新增/编辑
const funAdd = async () => {
  try {
    loading.value = true
    const url = form.id 
      ? 'api/MasterData/UpdateSupplier'
      : 'api/MasterData/CreateSupplier'
    
    await http.post(url, form)
    ElMessage.success(form.id ? '更新成功' : '新增成功')
    dialogFormVisible.value = false
    funShow()
  } catch (error: any) {
    ElMessage.error((form.id ? '更新' : '新增') + '失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 编辑供应商
const handleEdit = (row: any) => {
  Object.assign(form, row)
  dialogFormVisible.value = true
}

//删除供应商
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该供应商?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 调用删除 API
    http.post("api/MasterData/DeleteSupplier",row).then(() => {
      ElMessage.success('删除成功')
      funShow()
    }).catch((error: any) => {
      ElMessage.error('删除失败：' + error.message)
    })
  })
}

// 初始化
onMounted(() => {
  funShow()
})
</script>

<style scoped>
.supplier-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  padding: 16px;
}

.table-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.header-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #409eff;
  border-radius: 2px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
}

.supplier-form {
  padding: 24px 16px;
}

.dialog-footer {
  text-align: right;
  padding: 16px 0 0;
  border-top: 1px solid #ebeef5;
  margin-top: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-table) {
  margin-top: 16px;
  border-radius: 4px;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #303133;
  font-weight: 500;
  height: 48px;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--border) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  background-color: #fff;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-button) {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button--primary) {
  background-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c inset;
}

:deep(.el-form-item.is-success .el-input__wrapper) {
  box-shadow: 0 0 0 1px #67c23a inset;
}
</style>
